<?php

namespace app\nideshop\controller;

use think\Db;
use app\nideshop\service\Token;
use app\nideshop\validate\GoodsValidate;

class Search extends Base
{
	protected $datas;

	/**
	 * 搜索页面数据
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-29T20:52:47+0800
	 * @return   [type]                   [description]
	 */
	public function indexAction()
	{
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		// 取出输入框默认的关键词
    	$defaultKeyword = Db::name('keywords')->where('is_default', 1)->limit(1)->find();
    	// 取出热闹关键词
    	$hotKeywordList = Db::name('keywords')
	    	->distinct('keyword', true)
	    	->field('keyword,is_hot')
	    	->limit(10)
	    	->select();
    	$historyKeywordList = Db::name('search_history')
	    	->distinct('keyword', true)
	    	->where('user_id', $userId)
	    	->limit(10)
	    	->column('keyword');
	    return json([
            'errno' => 0,
            'errmsg' => '',
            'data' => [
                'defaultKeyword' => $defaultKeyword,
                'historyKeywordList' => $historyKeywordList,
                'hotKeywordList' => $hotKeywordList
            ]
        ]);
	}

	/**
	 * 搜索帮助
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-29T20:53:43+0800
	 * @return   [type]                   [description]
	 */
	public function helperAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new GoodsValidate, 'helper', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$keyword = $this->datas['keyword'];
		$keywords = Db('keywords')
			->distinct('keyword', true)
			->where('keyword','like', '%' . $keyword . '%')
			->limit(10)
			->column('keyword');
    	return json([
            'errno' => 0,
            'errmsg' => '',
            'data' => [
                'keywords' => $keywords,
            ]
        ]);
	}

	/**
	 * 清除历史
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-29T20:58:35+0800
	 * @return   [type]                   [description]
	 */
	public function clearhistoryAction()
	{
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$result = Db::name('search_history')->where('user_id', $userId)->delete();
		if (!$result) {
			return json(['errno' => 400, 'errmsg' => '失败', 'data' => []]);
		}
    	return json([
            'errno' => 0,
            'errmsg' => '',
            'data' => []
        ]);
	}
}